
import random
import ctypes
import ctypes.wintypes
import win32gui
from airtest.core.api import *

from common.common_util import get_all_windows


def get_hwnds(id):
    '''
    根据窗口标题获取对应句柄值
    :param id: 含有某个字段
    :return:
    '''
    hwnds = get_all_windows("记事本")
    for i in range(len(hwnds)):
        title = win32gui.GetWindowText(hwnds[i])
        if id in title:
            hwnd = hwnds[i]
            return hwnd
def get_postion(hwnd):
    '''
    根据句柄获取窗口位置
    :param hwnd: 句柄值
    :return:
    '''

    # 获取窗口左上角坐标和右下角坐标
    left, top, right, bottom = get_window_rect(hwnd)
    # 输出坐标信息
    print('窗口左上角坐标：({}, {})'.format(left, top))
    print('窗口右下角坐标：({}, {})'.format(right, bottom))
    return left, top,right, bottom

def get_window_rect(hwnd):
    try:
        f = ctypes.windll.dwmapi.DwmGetWindowAttribute
    except WindowsError:
        f = None
    if f:
        rect = ctypes.wintypes.RECT()
        DWMWA_EXTENDED_FRAME_BOUNDS = 9
        f(ctypes.wintypes.HWND(hwnd),
          ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
          ctypes.byref(rect),
          ctypes.sizeof(rect)
          )
        return rect.left, rect.top, rect.right, rect.bottom






def windows_swipe_zg(pc_sreen,posc_number,length):
    '''
    将窗口移动到指定为止，posc_number = [row,col]
    :param pc_sreen: pc分辨率（1920,1080）
    :param posc_number: 位置编号 [row,col]
    :param length: 缩放后的长度
    :return:
    '''
    hwnd  = get_hwnds("txt")
    connect_device(f'Windows:///{hwnd}')
    left, top, right, bottom = get_window_rect(hwnd)
    # 窗口移动右上角，方便缩放
    start_x = (left + right)/2
    start_y = top + 20
    end_x = (right - left)/2
    end_y = 20
    connect_device(f'Windows:///')
    swipe((start_x,start_y),(end_x,end_y),duration=1, steps=random.randint(4,10))

    # 缩放操作
    sleep(2)
    left, top, right, bottom = get_window_rect(hwnd)
    start_x = right
    start_y = (top + bottom)/2
    end_x = left + length
    end_y = start_y # 根据x缩放进行缩放
    swipe((start_x, start_y), (end_x, end_y), duration=2, steps=random.randint(4, 10))


    # # 移动操作
    sleep(2)
    left, top, right, bottom = get_window_rect(hwnd)
    start_x = (left + right)/2
    start_y = top + 20
    end_x = (left + right)/2 + (right-left)*posc_number[1]
    end_y = start_y + (bottom-top)*posc_number[0]
    if end_y > pc_sreen[1]:
        end_y = pc_sreen[1] - 40 - (right-left)
    swipe((start_x,start_y),(end_x,end_y), duration=2, steps=random.randint(4, 10))


if __name__ == '__main__':
    windows_swipe_zg((1920,1080),[1,1],600)



